<?php

namespace plugins\store\controller;

use cmf\controller\ApiPluginBaseController;
use think\Db;
use plugins\store\model\StoreCollectModel;
use plugins\member\model\MemberModel;


class ApiStoreCollectController extends ApiPluginBaseController
{
	//收藏列表
	public function collectList()
	{
		$param = $this->request->post();
		//带有info的token
		$info = $this->getIdentity();

		$member = ( new \plugins\member\model\MemberModel )->get(['uid'=>$info->uid]);
		if($member == null){
			return api_json_echo( false, '不存在的账号，请重试');			
		}

		$list = ( new StoreCollectModel )->field('id,uid',true)->where(['uid'=>$info->uid])->select()->toArray();

		if($list != ""){
			foreach ($list as $key => &$value) {
				$store = ( new \plugins\store\model\StoreModel )->get(['store_id'=>$value['store_id']]);
				$value['store_name'] = $store->store_name;
				if($store->store_log){
					$value['store_log'] = zy_domain().'/plugins/store/view/image/'.$store->store_log;
				}else{
					$value['store_log'] = $store->store_log;
				}
				
			}

			return api_json_echo(true,'查询完成',$list);
		}

		return api_json_echo( true , '查询完成，但是没有数据',null);


	}


	//加入收藏
	public function addCollect()
	{
		$post = $this->request->post();
		//带有info的token
		$info = $this->getIdentity();

		$member = ( new MemberModel )->get(['uid'=>$info->uid]);
		if($member == null){
			return api_json_echo( false, '不存在的账号，请重试');			
		}

		$count = ( new StoreCollectModel )->where(['store_id'=>$post['store_id'],'uid'=>$info->uid])->count();
		if($count != 0){
			return api_json_echo( false, '已收藏的店铺');	
		}

		$data['store_id'] = $post['store_id'];
		$data['uid'] = $info->uid;
		$data['time'] = time();
		$result = ( new StoreCollectModel )->data($data)->save();

		if($result){
			return api_json_echo( true, '收藏完成');	
		}
		return api_json_echo( false, '收藏失败');	
	}

	//取消收藏
	public function cancelCollect()
	{
		$post = $this->request->post();
		//带有info的token
		$info = $this->getIdentity();

		$member = ( new MemberModel )->get(['uid'=>$info->uid]);
		if($member == null){
			return api_json_echo( false, '不存在的账号，请重试');			
		}

		$count = ( new StoreCollectModel )->where(['store_id'=>$post['store_id'],'uid'=>$info->uid])->count();
		if($count == 0){
			return api_json_echo( false, '未收藏该店铺');	
		}

		$data['store_id'] = $post['store_id'];
		$data['uid'] = $info->uid;	
		
		$result = ( new StoreCollectModel )->destroy($data);	

		if($result){
			return api_json_echo( true, '已取消收藏');	
		}
		return api_json_echo( false, '取消收藏完成');		

	}
}